package com.guoranhao.tool.utils;

import java.util.Locale;
import java.util.Random;
import java.util.UUID;

/**
 * Description: Token生成规则
 * Copyright (c) Department of Research and Development/Beijing
 * All Rights Reserved.
 *
 * @version 1.0  2018年9月25日 上午10:54:48  by 张建飞（zhangjf@cloud-young.com）创建
 */
public class TokenGenerator {

    public static final String strGroup = "abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static final int tokenLength = 64;

    /**
     * Description: 生成token
     * 规则：单位时间戳内为用户生成唯一UUID
     * 主要就是三部分：时间戳，用户id,UUID 时间戳13位，uuid 32位，用户id length*2+1，其余补随机数
     *
     * @return
     * @Version1.0 2018年9月25日 上午10:57:06 by 张建飞（zhangjf@cloud-young.com）创建
     */
    public static String createToken(Long userId) {
        String timestampStr = timeGen();
        String userIdStr = userIdGen(userId);
        String uuidStr = uuidGen();
        String prefix = userIdStr.length() < 9 ? "0" : (userIdStr.length() / 10) + "";
        String suffix = userIdStr.length() < 9 ? userIdStr.length() + "" : (userIdStr.length() % 10) + "";
        String randomStr = randomString(tokenLength - timestampStr.length() - uuidStr.length() - userIdStr.length() - 2);

        return prefix + timestampStr + userIdStr + uuidStr + randomStr + suffix;
    }

    /**
     * Description: 解析token，参照生成规则反向解析
     *
     * @param token
     * @return
     * @Version1.0 2018年9月25日 下午2:03:44 by 张建飞（zhangjf@cloud-young.com）创建
     */
    public static Long analysisToken(String token) {
        try {
            if (StringUtil.isEmpty(token) || token.length() < tokenLength) {
                return -1L;
            }
            int userIdStrLength = Integer.parseInt(token.substring(0, 1) + token.substring(token.length() - 1));
            String userIdStr = token.substring(1 + 13, 1 + 13 + userIdStrLength);

            StringBuffer sbBuffer = new StringBuffer();
            for (int i = 0; i < userIdStr.length(); i++) {
                if (i % 2 == 0) {
                    sbBuffer.append(userIdStr.charAt(i));
                }
            }
            return Long.parseLong(sbBuffer.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1L;
    }

    public static String timeGen() {
        return System.currentTimeMillis() + "";
    }

    public static String uuidGen() {
        String originUUID = UUID.randomUUID().toString().replace("-", "");
        return originUUID.toUpperCase(Locale.CHINA);
    }

    public static String userIdGen(Long userId) {
        String userIdStr = String.valueOf(userId == null ? 0 : userId);
        StringBuffer sbBuffer = new StringBuffer();
        for (int i = 0; i < userIdStr.length(); i++) {
            sbBuffer.append(userIdStr.charAt(i)).append(randomString(1));
        }
        return sbBuffer.toString();
    }

    public static String randomString(int length) {
        if (length <= 0) {
            return "";
        }
        Random r = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int index = r.nextInt(strGroup.length());
            buffer.append(strGroup.charAt(index));
        }
        return buffer.toString().toUpperCase(Locale.CHINA);
    }

}
